package com.wlld.tools;


import com.wlld.MatrixTools.Matrix;
import com.wlld.MatrixTools.MatrixOperation;

import java.util.Random;

/**
 * @param
 * @DATA
 * @Author LiDaPeng
 * @Description rgb三通道回归期望值 B = wr *R + wg * G+b
 */
public class RgbRegression {
    private double r;
    private double g;
    private double b;
    private Matrix RG;//rgb矩阵
    private Matrix B;//b矩阵
    private boolean isRegression = false;//是否进行了回归
    private int regionNub;
    private int x;
    private int y;


    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public Matrix getRGMatrix() {
        return RG;
    }

    public Matrix getBMatrix() {
        return B;
    }

    public int getRegionNub() {
        return regionNub;
    }

    public void setRegionNub(int regionNub) {
        this.regionNub = regionNub;
    }


    public double getB() {
        return b;
    }

    public RgbRegression(int size) throws Exception {//初始化rgb矩阵
        RG = new Matrix(size, 4);
        B = new Matrix(size, 1);
        regionNub = size;
        Random random = new Random();
        double oneSize = 1D / size;
        for (int i = 0; i < size; i++) {
            //double t = oneSize * i;
            RG.setNub(i, 0, random.nextDouble());
            RG.setNub(i, 1, random.nextDouble());
            RG.setNub(i, 2, random.nextDouble());
            RG.setNub(i, 3, 1.0);
        }

    }

    public void insertRGB(double[] value) throws Exception {//rgb插入矩阵
        if (value.length == regionNub) {
            for (int i = 0; i < regionNub; i++) {
                B.setNub(i, 0, value[i]);
            }
        } else {
            throw new Exception("rgb length is not equals three");
        }
    }

    public boolean regression() throws Exception {//开始进行回归
        if (regionNub > 0) {
            Matrix ws = MatrixOperation.getLinearRegression(RG, B);
            if (ws.getX() == 1 && ws.getY() == 1) {//矩阵奇异
                isRegression = false;
            } else {
                r = ws.getNumber(0, 0);
                g = ws.getNumber(1, 0);
                b = ws.getNumber(2, 0);
                isRegression = true;
            }
            return isRegression;
            // System.out.println("wr==" + wr + ",wg==" + wg + ",b==" + b);
        } else {
            throw new Exception("regression matrix size is zero");
        }
    }

    public double getR() {
        return r;
    }

    public double getG() {
        return g;
    }
}
